<template>
  <div class='infinite-container'>
    <div class="progress-wrap">
      <mu-linear-progress :size="8" color="#F0FFF6" mode="determinate" :value="value"/>
      已完成进度：{{value}}%
    </div>
    <template  v-for='(d, i) in qadata'>
      <div class='qa'  :key='i' v-show='d.show'>
          <qa-item :d='d' :key='i'></qa-item>
          <!-- <div class='progress'>{{(currentPage+1) + '/' + qadata.length}}</div> -->
      </div>
    </template>
  
    <mu-flexbox class='qa-login login bgwhite' :gutter='2'>
      <mu-flexbox-item>
        <mu-raised-button label='上一题' primary fullWidth class='btn-login' @click='goPage(-1)' :disabled='currentPage === 0'>
        </mu-raised-button>
        </mu-flexbox-item>
        <mu-flexbox-item>
           <mu-raised-button label='下一题' primary fullWidth class='btn-login' @click='goPage(1)' v-if='currentPage !== (qadata.length - 1)' ></mu-raised-button>
             <mu-raised-button label='提交' fullWidth primary class='btn-login' @click='submit' v-else></mu-raised-button>
        </mu-flexbox-item>
    </mu-flexbox>
  </div>
</template>

<script>
import {commonAjax, commonAjaxJson, RESTFUL_API} from '@/api/api'
import QaItem from '@/components/QaItem'
export default {
  components: {QaItem},
  data () {
    return {
      qadata: [],
      currentPage: 0,
      person: JSON.parse(sessionStorage.familyPerson || '{}'),
      currentQuestionnaire: JSON.parse(sessionStorage.currentQuestionnaire || '{}')
    }
  },
  computed: {
    value () {
      if (this.qadata.length === 0) {
        return 0
      }
      return Math.floor((this.currentPage + 1) / this.qadata.length * 100)
    }
  },
  mounted () {
    this.getById()
  },
  methods: {
    getById () {
      if (!this.$route.query.type) {
        return
      }
      this.$store.commit('UPDATE_LOADING')
      commonAjax(`${RESTFUL_API.getByType}/${this.$route.query.type}`, {}, true).then(res => {
        this.$store.commit('UPDATE_LOADING')
        if (res.data.code === 1) {
          if (Array.isArray(res.data.data.questionsubjectBean) && res.data.data.questionsubjectBean.length > 0) {
            this.qadata = this.getList(res.data.data.questionsubjectBean)
          }
        } else {
          this.$store.commit('UPDATE_TOAST', {
            message: res.data.msg || '服务器错误'
          })
        }
      })
    },
    createResult (params) {
      this.$store.commit('UPDATE_LOADING')
      commonAjaxJson(RESTFUL_API.createResult, params, true).then(res => {
        this.$store.commit('UPDATE_LOADING')
        if (res.data.code === 1) {
          this.$store.commit('UPDATE_TOAST', {
            message: res.data.msg || '提交成功',
            fn: () => this.$router.replace('/questionnaire/thankyou')
          })
        } else {
          this.$store.commit('UPDATE_TOAST', {
            message: res.data.msg || '提交失败'
          })
        }
      }).catch(e => {
        console.warn(e.message)
        this.$store.commit('UPDATE_LOADING')
      })
    },
    getList (arr) {
      let temp = []
      arr.forEach((v, i) => {
        if (v.typecode === 'radio') {
          // todo
          // add options for radio
          let tempOptions = []
          v.questionanswerBean.forEach(v1 => {
            tempOptions.push({
              label: v1.answer,
              value: v1.qid + '',
              infoqid: v1.infoqid,
              subjectqid: v1.subjectqid,
              inquirer: this.person.id
            })
          })
          temp.push({
            type: 'radio',
            title: v.subject,
            model: '',
            show: i === this.currentPage,
            options: tempOptions
          })
        } else if (v.typecode === 'checkbox') {
          // todo
          let tempOptions = []
          v.questionanswerBean.forEach(v1 => {
            tempOptions.push({
              label: v1.answer,
              value: v1.qid + '',
              infoqid: v1.infoqid,
              subjectqid: v1.subjectqid,
              inquirer: this.person.id
            })
          })
          temp.push({
            type: 'checkbox',
            title: v.subject,
            model: [],
            show: i === this.currentPage,
            options: tempOptions
          })
        } else if (v.typecode === 'content') {
          // todo
          let tempOptions = []
          tempOptions.push({
            value: v.qid + '',
            model: '',
            XMLB: 7, // show input
            infoqid: v.infoqid,
            subjectqid: v.qid,
            inquirer: this.person.id
          })
          temp.push({
            type: 'input',
            title: v.subject,
            show: i === this.currentPage,
            options: tempOptions
          })
        }
      })
      return temp
    },
    goPage (page) {
      this.currentPage += page
      if (this.currentPage >= this.qadata.length) {
        return
      }
      this.qadata.forEach((v, i) => {
        v.show = i === this.currentPage
      })
    },
    getAnseredList () {
      let temp = []
      this.qadata.forEach(v => {
        if (v.type === 'input') {
          // todo
          temp = temp.concat(this.addInputAnswer(v))
        } else if (v.type === 'checkbox') {
          // todo
          temp = temp.concat(this.addCheckboxAnswer(v))
        } else if (v.type === 'radio') {
          // todo
          temp = temp.concat(this.addRadioAnswer(v))
        }
      })
      console.log(temp)
      return temp
    },
    addInputAnswer (v) {
      let temp = []
      if (v.options[0].model.length > 0) {
        let input = v.options[0]
        temp.push({
          // qId: input.value,
          inquirer: input.inquirer,
          infoqid: input.infoqid,
          subjectqid: input.subjectqid,
          content: input.model
        })
      }
      return temp
    },
    addRadioAnswer (v) {
      let temp = []
      if (v.model.length > 0) {
        let v2 = v.options[0]
        temp.push({
          // qId: v2.value,
          inquirer: v2.inquirer,
          infoqid: v2.infoqid,
          subjectqid: v2.subjectqid,
          answerqid: +v.model
        })
      }
      return temp
    },
    addCheckboxAnswer (v) {
      let temp = []
      if (v.model.length > 0) {
        v.model.forEach(v1 => {
          v.options.forEach(v2 => {
            if (v1 === v2.value) {
              temp.push({
                // qId: v.value,
                inquirer: v2.inquirer,
                infoqid: v2.infoqid,
                subjectqid: v2.subjectqid,
                answerqid: +v2.value
              })
            }
          })
        })
      }
      return temp
    },
    submit () {
      // todo
      let params = this.getAnseredList()
      if (params.length === 0) {
        this.$store.commit('UPDATE_TOAST', {message: '请先填写问卷'})
        return
      }
      this.createResult({
        recordid: this.currentQuestionnaire.recordId,
        inquirer: this.person.id || '',
        visittime: Date.now(),
        doctorcode: this.currentQuestionnaire.doctorCode,
        doctorname: this.currentQuestionnaire.doctorName,
        departmentname: this.currentQuestionnaire.departmentName,
        departmentcode: this.currentQuestionnaire.departmentCode,
        questionresultBean: params
      })
    }
  }
}
</script>

<style lang='less'>
@import '../../common/css/vars.less';
.qa-login {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    z-index: 10;
  }
  .progress-wrap{
    background: url(../../assets/images/manyidu_bg.png);
    background-size: 100%;
    height: 112px;
    padding: 40px 20px;
    position: absolute;
    z-index: 10;
    right: 0;
    top: 0;
    left: 0;
    color: #fff;
    .mu-linear-progress{
      background-color: #00B766;
    }
  }
.qa {
  border-bottom: 1px solid @color-border;
  // border-top: 3px solid @color-primary;
  background:#fff;
  margin-bottom: 1em;
  padding:130px 10px 10px 10px;
  .title {
    color:#999;
    padding-bottom: 1em;
  }
  
  .progress {
    // background: #fff;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    color: #999;
  }
  .mu-text-field-input {
    border: 1px solid #eee;
    padding: 0 10px;
  }
}
</style>
